//
//  TextFieldAndTableViewCell.m
//  RACExample
//
//  Created by 山刘 on 2020/6/3.
//  Copyright © 2020 山刘. All rights reserved.
//

#import "TextFieldAndTableViewCell.h"

@implementation TextFieldAndTableViewCell
#pragma mark - init Views
+(NSString*)reuseIdentifier{
    return NSStringFromClass([self class]);
}

+(TextFieldAndTableViewCell*)cellWithTableView:(UITableView*)tableView indexPath:(NSIndexPath*)indexPath{
    TextFieldAndTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[self reuseIdentifier] forIndexPath:indexPath];
    if (!cell) {
        cell = [[TextFieldAndTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:[self reuseIdentifier]];
    }
    cell.indexPath = indexPath;
    return cell;
}

-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    if (self == [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        [self segInitViews];
        [self updateConstraints];
    }
    return self;
}

-(void)segInitViews{
    [self.contentView addSubview:self.inputTextField];
}

#pragma mark - Layout
- (void)updateConstraints {
    [self.inputTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.equalTo(self.contentView).mas_offset(5);
        make.right.bottom.equalTo(self.contentView).mas_offset(-5);
    }];
    [super updateConstraints];
}

#pragma mark - RAC Data Binding
- (void)bindViewModel {
    self.inputTextField.text = self.viewModel.inputValue;
    self.inputTextField.tag = self.viewModel.tag;
    
    @weakify(self)
    [[[[self.inputTextField rac_textSignal] takeUntil:self.rac_prepareForReuseSignal] filter:^BOOL(NSString * _Nullable value) {
        NSLog(@"filter -- %@", value);
        return YES;
    }] subscribeNext:^(NSString * _Nullable x) {
        @strongify(self);
        NSLog(@"subscribeNext %@ tag:%zd",x,self.inputTextField.tag);
        self.viewModel.inputValue = x;
    }];
}

#pragma mark - getter

#pragma mark setter
-(void)setViewModel:(TextFieldAndTableViewCellViewModel *)viewModel{
    _viewModel = viewModel;
    if (!viewModel)  return;
    [self bindViewModel];
}

-(UITextField *)inputTextField{
    if (!_inputTextField) {
        _inputTextField = [[UITextField alloc] init];
        _inputTextField.font = [UIFont systemFontOfSize:16];
        _inputTextField.textColor = [UIColor blackColor];
        _inputTextField.tintColor = [UIColor blackColor];
    }
    return _inputTextField;
}
@end
